package com.ysdcrm.crm.controller;

import java.util.List;

import javax.annotation.Resource;

import com.ysdcrm.crm.mapper.IRoleModuleRelationMapper;
import com.ysdcrm.crm.mapper.IRolesMapper;
import com.ysdcrm.crm.model.RoleModuleRelation;
import com.ysdcrm.crm.model.Roles;

import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import io.swagger.annotations.ApiOperation;

@RestController
@RequestMapping("role")
@ApiOperation(value = "角色管理")
public class RolesController {
    @Resource
    private IRolesMapper mapper;

    @Resource
    private IRoleModuleRelationMapper rMapper;

    @GetMapping
    @ApiOperation(value = "查询所有角色")
    public List<Roles> findAll(){
        return mapper.selectList(null);
    }

    @PostMapping
    @ApiOperation(value = "添加角色",notes = "角色名不可重复")
    public int add(Roles r){
        if(mapper.getNameCount(r.getName())>0){
            return 0;
        }else{
            return mapper.insert(r);
        }
    }

    @PutMapping
    @ApiOperation(value = "修改角色名称",notes = "名称不可重复")
    public int edit(Roles r){
        if(mapper.getNameCount(r.getName())>0){
            return 0;
        }else{
            return mapper.updateById(r);
        }
    }

    @DeleteMapping
    @ApiOperation(value = "删除角色",notes = "逻辑删除")
    public int del(int rid){
        return mapper.del(rid);
    }

    @ApiOperation(value = "分配权限")
    @PostMapping("set")
    public int addRole(List<RoleModuleRelation> list){
        //分配权限前先要清空原有的权限（暂时未做）
        int n = 0;
        for(RoleModuleRelation r: list){
            n += rMapper.insert(r);
        }
        return n;
    }

}
